package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.common.exception.CustomException;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.Item;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        LambdaQueryWrapper<PurchaseEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(PurchaseEntity::getStatus, Arrays.asList(WareConstant.PurchaseStatusEnum.CREATED.getCode(), WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()));
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
              wrapper
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void merge(PurchaseVo purchaseVo) {
        //1.更新采购单，没有则创建，有则更新
        Long purchaseId = purchaseVo.getPurchaseId();
        if (StringUtils.isEmpty(purchaseId)) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setPriority(0);
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();
        }else {
            PurchaseEntity purchaseEntity = this.getById(purchaseId);
            Integer status = purchaseEntity.getStatus();
            if (!status.equals(WareConstant.PurchaseStatusEnum.CREATED) || !status.equals(WareConstant.PurchaseStatusEnum.ASSIGNED)) {
                throw new CustomException("该采购单不合法", 500);
            }
        }
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

        //2.更新采购项
        List<Long> ids = purchaseVo.getItems();
        List<PurchaseDetailEntity> detailEntities = detailService.list(new LambdaQueryWrapper<PurchaseDetailEntity>().in(PurchaseDetailEntity::getId, ids));
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntityList = detailEntities.stream().map(item -> {
            item.setPurchaseId(finalPurchaseId);
            item.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return item;
        }).collect(Collectors.toList());
        detailService.updateBatchById(detailEntityList);
    }

    @Override
    public void receivedPurchase(List<Long> purchaseIdList) {
        //1.更新采购单
        List<PurchaseEntity> list = this.list(new LambdaQueryWrapper<PurchaseEntity>().in(PurchaseEntity::getId, purchaseIdList));
        List<PurchaseEntity> collect = list.stream().map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(list);

        //2、更新采购项
        List<PurchaseDetailEntity> entityList = detailService.list(new LambdaQueryWrapper<PurchaseDetailEntity>().in(PurchaseDetailEntity::getPurchaseId, purchaseIdList));
        for (PurchaseDetailEntity purchaseDetailEntity : entityList) {
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
        }
        detailService.updateBatchById(entityList);

    }

    @Override
    public void finishPurchase(PurchaseDoneVo doneVo) {
        //1、更新采购单
        Long id = doneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        List<Item> items = doneVo.getItems();
        List<PurchaseDetailEntity> details = new ArrayList<>();

        for (Item item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());
            detailEntity.setReason(item.getReason());
            detailEntity.setStatus(item.getStatus());
            details.add(detailEntity);
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()) {
               //采购失败
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
            }else {
                //采购成功，更新库存
                PurchaseDetailEntity detail = detailService.getById(item.getItemId());
                wareSkuService.updateStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum());
            }
        }
        this.updateById(purchaseEntity);

        //2、更新采购项
        detailService.updateBatchById(details);






    }


}
